package com.gollum.common.web.controller;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson2.JSONObject;
import com.gollum.common.context.PageContextHolder;
import com.gollum.jpa.domain.PageQueryRequest;
import com.gollum.common.utils.ServletUtils;
import com.gollum.common.utils.ip.IpUtils;

import java.util.Objects;

/**
 * 抽象Controller层
 *
 * @author Herther
 * @version 1.0.0
 * @createTime 2022年08月28日 21:24:00
 */
public class BaseController {



    private final String PAGE_NAME = "page";

    private final String PAGE_SIZE_NAME = "pageSize";

    private final String  SORTED_NAME  = "sorted";

    private final String  FILTER  = "filter";

    /**
     * 获取当前请求ip地址
     *
     * @auther: Herther
     * @version 1.0.0
     * @date: 2022/8/28 21:25
     */
    public String getIpAddr(){
        return IpUtils.getIpAddr(ServletUtils.getRequest());
    }

    /**
     * 构建分页线程
     * @auther: Herther
     * @since 1.0.0
     * @date: 2022/9/14 22:16
     */
    public void buildPageQuery(JSONObject jsonObject){

        Integer page = Convert.toInt(jsonObject.get(PAGE_NAME));
        Integer pageSize = Convert.toInt(jsonObject.get(PAGE_SIZE_NAME));
        String sorted = Objects.isNull(jsonObject.get(SORTED_NAME)) ? "" : Convert.toStr(jsonObject.get(SORTED_NAME));
        Object filter = jsonObject.get(FILTER);
        if(Objects.isNull(filter)){
            filter = "";
        }
        PageContextHolder.set(new PageQueryRequest(page, pageSize, sorted,filter.toString()));
    }

    /**
     * 清理分页线程
     *
     * @auther: Herther
     * @since 1.0.0
     * @date: 2022/9/14 22:20
     */
    public void clearPageThead(){
        PageContextHolder.remove();
    }

    /**
     *
     * 将查询参数转实体
     *
     * @auther: Herther
     * @since 1.0.0
     * @date: 2022/9/14 22:20
     */
    public <T> T toJavaObjectParams(Class<?> clazz, JSONObject jsonObject){
        return (T) jsonObject.to(clazz);
    }



}
